const http = require('http');

const host = 'http://ifnews.com/';

function start() {
  return new Promise((resolve, reject) => {
    try {
      const server = http.createServer((req, res) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        res.end('Hello World\n');
      });
      
      server.listen(2580, () => {
        resolve('Server running at http://localhost:2580/');
        // console.log('Server running at http://localhost:2580/');
      });
      
    } catch (error) {
      reject(error)
    }
  });
}
const awaitTime = (time) => new Promise((r) => {setTimeout(r,time)});

async function onSearch(name, browser) {
  return new Promise(async (resolve, reject) => {
    try {
      const page = await browser.newPage();
      page.on('response', async(res) => {
        if (res.url().indexOf('/cmsapi/searchArticle')) {
          const result = await res.json();
          resolve(result.list);
        }
      });
      await page.goto(`${host}searchColumn.html`, {waitUntil: 'domcontentloaded'});
      await page.waitForSelector('.el-input__inner');
      await page.focus('.input-with-select>.el-input__inner');
      await awaitTime(500);
      await page.type('.input-with-select>.el-input__inner', name, {delay: 100});
      await awaitTime(500);
      await page.click('.el-input__inner+.el-input-group__append .el-button.el-button--default');
    } catch (error) {
      reject(error);
      await browser.close();
    }
  });
}

async function onStart(id, browser) {
  return new Promise(async (resolve, reject) => {
    try {
      const page = await browser.newPage();
      page.on('response', async(res) => {
        // 过滤掉method为option的返回
        if (res.url().endsWith('/api/event') && res.request().method() == 'POST') {
          const result = await res.json();
          resolve(result);
        }
      });
      await page.goto(`${host}news.html?aid=${id}`);
    } catch (error) {
      reject(error);
      await browser.close();
    }
  });
}


module.exports.awaitTime = awaitTime;
module.exports.serverStart = start;
module.exports.onSearch = onSearch;
module.exports.onStart = onStart;